import { Injectable } from '@nestjs/common';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../modules/user/user.service';
import { User } from 'src/modules/user/entities/user.entity';
import { NewUser } from 'src/modules/user/entities/user.entity.new';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  async validateUser(
    username: string,
    password: string,
  ): Promise<null | Omit<NewUser, 'password'>> {
    const existUser = await this.userService.findByUsername(username);
    console.log(existUser);
    if (!existUser) {
      return null;
    }

    // const isMatch = await bcrypt.compare(password, existUser.password);
    const isMatch = password === existUser.password;
    // console.log('25', password, existUser.password);
    // console.log('26', isMatch);
    if (!isMatch) {
      return null;
    }

    const { password: ignorePass, ...restUser } = existUser;
    // console.log('32', restUser);
    return restUser;
  }

  async login(user: NewUser) {
    const { password, ...restUser } = user;

    const payload = { ...restUser, sub: user.id };

    return {
      token: this.jwtService.sign(payload),
      user: restUser,
      // expiresIn: jwtConstants.expiresIn,
    };
  }
}
